/*
*	Routine for delaying a specified amount of time (n seconds)
*
*	Author: ORC
*
* 	Copyright (c) Altera Corporation 2002.
* 	All rights reserved.
*/

#include <stdio.h>
#include <time.h>
#include <signal.h>

#include "timer.h"
#include "hs_types.h"
#include "mac_debug.h"
#include "timer00.h"
//#include "isr_timer.h"
#include "mac_timer.h"
#include "PmdGlobals.h"
#include "errno.h"

#include <os/ostrace.h>
#include <os/interrupt.h>
#include <os/driver.h>
#include <machine/mmio.h>
#include <machine/machdefs.h>

#include "nmpt_defines.h"

volatile HS_INT32 timer_initval;
volatile HS_INT32 hsn_clockscale;

volatile HS_INT32 timer_type;
volatile timer_t timer_id;
volatile struct itimerspec  new_time,old_time;

void check_timer()
{
	union sigval sigval = {0};

	HS_UINT32 bit;

	if(get_timer_type() != FREE_TIMER){
		bit = *(volatile HS_UINT32*)(NMPT_INTR_CNTRL_BASE+NMPT_INTR_STATUS)&0x1;
		if(bit != 0){
			isr_timer(sigval);
		}
	}
}
HS_INT32 get_timer_interrupt(){
	HS_UINT32 bit;
	bit = *(volatile HS_UINT32*)(NMPT_BASE+NMPT_CTRL)&0x80;
	if(bit == 1){
		return 1;
	}
	return 0;
}

void init_timer(void)
{
	hsn_clockscale = (1<<16)/HSN_1USEC;
printf("HSN_1USEC = %d\n",HSN_1USEC);
    set_timer_type(FREE_TIMER);

	/* Enable timer0 interrupts */
	*(volatile HS_UINT32*)(NMPT_INTR_CNTRL_BASE+NMPT_INTR_EN) = 0x1;
}

/* These files for Channel Acquiration Timer  and Ack Timer */
/** limit is in uSec **/
void set_timer_limit(HS_INT32 limit)
{
	timer_initval =
	*(volatile HS_UINT32*)(NMPT_BASE+NMPT_START) = (0xFFFFFF-HSN_1USEC*limit);
	*(volatile HS_UINT32*)(NMPT_BASE+NMPT_COMPARE) = 0;
	*(volatile HS_UINT32*)(NMPT_BASE+NMPT_CTRL) = 0x00003A6F;
	*(volatile HS_UINT32*)(NMPT_BASE) = 0; //presc
	*(volatile HS_UINT32*)(NMPT_BASE+NMPT_ADJ) = 0x00400000;
}

HS_INT32 stop_timer(void )
{
	HS_UINT32 bit;
	HS_INT32 value;

	value = *(volatile HS_UINT32*)(NMPT_BASE+NMPT_START) - timer_initval;
	value = (value*hsn_clockscale) >> 16;

	*(volatile HS_UINT32*)(NMPT_BASE+NMPT_ADJ) = 0;

	/* If the timer already expired: clear the interrupt */
	bit = *(volatile HS_UINT32*)(NMPT_INTR_CNTRL_BASE+NMPT_INTR_STATUS)&0x1;
	if(bit != 0){
		*(volatile HS_UINT32*)(NMPT_INTR_CNTRL_BASE+NMPT_INTR_STATUS) = 0x1;
	}

	set_timer_type(FREE_TIMER);

	return value;
}

HS_INT32 current_timer_value()
{
	HS_INT32 value;

	value = *(volatile HS_UINT32*)(NMPT_BASE+NMPT_START) - timer_initval;
	value = (value*hsn_clockscale) >> 16;

	return value;
}

void set_timer_type(HS_INT32 type)
{
    timer_type=type;
}

HS_INT32 get_timer_type()
{
    return timer_type;
}

